package builderObserver;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import furnitureBuilder.Bedroom;
import furnitureBuilder.BedroomBuilder;
import furnitureBuilder.Item;

public class builderObserver extends Observer{
	String fileName = null;
	public builderObserver(BedroomBuilder subject) {
		this.subject = subject;
		this.subject.attachObserver(this);
	}

	@Override
	public void saveToFile(Bedroom room) {
		
		String fileName;
		BufferedWriter fileWriter = null;
		try {
			
			System.out.println("---------- Start write file ------------");
			Calendar calendar = Calendar.getInstance();
			fileName = calendar.getTime().toString().replaceAll(":", "_").replaceAll("\\s", "_");
			fileWriter = new BufferedWriter(new FileWriter(fileName + ".txt", true));
			fileWriter.newLine();
			fileWriter.write("--------- " + calendar.getTime() + " ---------------");
			fileWriter.newLine();
			List<Item> items = room.getItems();
			for(Item item : items){
				fileWriter.newLine();
				fileWriter.write("Item description: " + item.description());
				fileWriter.newLine();
				fileWriter.write("Item Lumber Type: "+ item.lumberType());
				int price = (int) item.price();
				fileWriter.newLine();
				fileWriter.write("Item Price: "+ price);
				fileWriter.newLine();
				fileWriter.write("------------------------------------");
				fileWriter.newLine();
			}
			fileWriter.write("Room total price: " + room.getTotalCost());
			fileWriter.newLine();
			fileWriter.write("------------End-------------");
			System.out.println("---------File was written successfully!-----------");
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			if (fileWriter != null) {
				try {
					fileWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}
}
